<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\LihuaBonus;
use app\common\model\LihuaExchange;
use app\common\model\LihuaSgoods;
use app\common\model\LihuaUseraddr;
use app\common\model\LihuaUserbonus;
use app\common\model\User;
use app\common\model\ScoreLog;

/**
 * 积分商城
 */
class Score extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 商城首页
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="city_id", type="int", required=true, description="城市id")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认20条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569511898","data":{"myscore":966600,"page":1,"total":16,"page_size":5,"total_page":4,"list":[{"id":182,"name":"20元大红包","type":2,"des":"大大红包嗨不停","pic":"https://lihua.czapi.cn/uploads/20190815/4aebff521a5bcb162f07fd78fa38add2.png","score":1200,"limit_num":0},{"id":170,"name":"银鹭花生牛奶（箱）","type":1,"des":"24盒装箱式银鹭花生牛奶一箱（5个工作日送达）","pic":"http://image.lihua.com/images/newweb/2018/12/thumb_5c1b14249eddc.jpg","score":3600,"limit_num":1},{"id":169,"name":"椰汁（箱）","type":1,"des":"24听装箱式椰汁一箱（5个工作日送达）","pic":"http://image.lihua.com/images/newweb/2018/12/thumb_5c1b1369b4bd6.jpg","score":8800,"limit_num":0}]}})
     */
    public function index()
    {
        $city_id = (int)$this->request->post('city_id', 0);
        if (!$city_id) $this->error('参数错误');

        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'myscore'    => $this->auth->score,//我的积分
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where = ['city_id' => $city_id, 'status' => 1];
        $total = LihuaSgoods::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $list = LihuaSgoods::where($where)->field('id,name,type,des,pic,score,limit_num')
                ->order('id', 'desc')->page($page, $page_size)->select();
            foreach ($list as $k => $v) {
                if (strpos($v['pic'], '/') === 0) $list[$k]['pic'] = config('site_url') . $v['pic'];
            }
            $data['list'] = $list;
        }

        $this->success('OK', $data);
    }

    /**
     * 立刻兑换
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="积分商品id")
     * @ApiParams   (name="num", type="int", required=true, description="兑换数量")
     * @ApiParams   (name="addr_id", type="int", required=true, description="收货地址ID，红包商品非必要")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569508843","data":{"excinfo":{"id":953,"city_id":3,"user_id":3,"sg_id":37,"sg_name":"海天酱油 老抽王","sg_type":1,"score":3600,"num":2,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":0,"dotime":0,"create_time":1569508843},"myscore":966600}})
     */
    public function exchange()
    {
        $id  = (int)$this->request->post('id', 0);
        $num = (int)$this->request->post('num', 1);
        $addr_id = (int)$this->request->post('addr_id', 0);
        if (!$id || $num < 1) $this->error('参数错误');

        $row = LihuaSgoods::get($id);
        if (!$row) $this->error('非法操作');
        if ($row['status'] == 0) $this->error('兑换商品已下架');

        if ($row['limit_num'] > 0) {
            if ($num > $row['limit_num']) $this->error("此商品限制兑换{$row['limit_num']}件");
            $cnt = LihuaExchange::where(['user_id' => $this->auth->id, 'sg_id' => $id])->count();
            if ($num > $row['limit_num'] - $cnt) $this->error("此商品限制兑换{$row['limit_num']}件，你已兑换{$cnt}件");
        }

        $score = $row['score'] * $num;
        if ($this->auth->score < $score) $this->error('积分不足');
        $myscore = $this->auth->score - $score;

        User::score(-$score, $this->auth->id, "兑换 {$row['name']} ×{$num}");

        $data = [
            'id'        => null,
            'city_id'   => $row['city_id'],
            'user_id'   => $this->auth->id,
            'sg_id'     => $row['id'],
            'sg_name'   => $row['name'],
            'sg_type'   => $row['type'],
            'score'     => $score,
            'num'       => $num,
            'consignee' => '',
            'mobile'    => '',
            'address'   => '',
            'dostat'    => $row['bonus_id'] > 0 ? 1 : 0,
            'dotime'    => $row['bonus_id'] > 0 ? time() : 0,
        ];

        if ($addr_id > 0) {
            $addr = LihuaUseraddr::get($addr_id);
            $data['consignee'] = $addr['consignee'];
            $data['mobile']    = $addr['mobile'];
            $data['address']   = $addr['name'] . $addr['house_num'];
        }

        $exc = LihuaExchange::create($data);

        if ($row['bonus_id'] > 0) {
            $bonus = LihuaBonus::get($row['bonus_id']);
            $days  = $bonus['days'] > 0 ? $bonus['days'] : 4;
            $userbonus = [
                'city_id'    => $bonus['city_id'],
                'user_id'    => $this->auth->id,
                'bonus_id'   => $bonus['id'],
                'name'       => $bonus['name'],
                'type'       => $bonus['type'],
                'reach'      => $bonus['reach'],
                'reduce'     => $bonus['reduce'],
                'des'        => $bonus['des'],
                'start_date' => date('Y-m-d'),
                'end_date'   => date('Y-m-d', strtotime("+{$days} day")),
            ];
            for($i = 0; $i < $num; $i++) {
                LihuaUserbonus::create($userbonus);
            }
        }

        $exc['id'] = (int)$exc['id'];
        $this->success('OK', ['excinfo' => $exc, 'myscore' => $myscore]);
    }

    /**
     * 兑换记录
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认20条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569509568","data":{"page":1,"total":5,"page_size":20,"total_page":1,"list":[{"id":953,"city_id":3,"user_id":3,"sg_id":37,"sg_name":"海天酱油 老抽王","sg_type":1,"score":3600,"num":2,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":0,"dotime":0,"domark":"","create_time":1569508843},{"id":952,"city_id":3,"user_id":3,"sg_id":128,"sg_name":"冰红茶","sg_type":1,"score":20400,"num":3,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":0,"dotime":0,"domark":"","create_time":1569508745},{"id":951,"city_id":3,"user_id":3,"sg_id":138,"sg_name":"天堂伞（丽华快餐纪念版）","sg_type":1,"score":5800,"num":1,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":0,"dotime":0,"domark":"","create_time":1569507298},{"id":950,"city_id":3,"user_id":3,"sg_id":42,"sg_name":"金龙鱼 玉米油","sg_type":1,"score":3600,"num":1,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":0,"dotime":0,"domark":"","create_time":1569506670},{"id":941,"city_id":3,"user_id":3,"sg_id":182,"sg_name":"20元大红包","sg_type":2,"score":2400,"num":2,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":1,"dotime":1569426909,"domark":"","create_time":1569426909}]}})
     */
    public function exclogs()
    {
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where['user_id'] = $this->auth->id;
        $total = LihuaExchange::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $list = LihuaExchange::where($where)->order('id', 'desc')->page($page, $page_size)->select();
            $data['list'] = $list;
        }

        $this->success('OK', $data);
    }

    /**
     * 兑换详情
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="兑换记录id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569508272","data":{"id":950,"city_id":3,"user_id":3,"sg_id":42,"sg_name":"金龙鱼 玉米油","sg_type":1,"score":3600,"num":1,"consignee":"吴大帝","mobile":"13961259813","address":"中源大厦502室","dostat":0,"dotime":0,"domark":"","create_time":1569506670}})
     */
    public function excinfo()
    {
        $id = $this->request->post('id', 0);
        if ($id) {
            $row = LihuaExchange::get(['id' => $id, 'user_id' => $this->auth->id]);
            if ($row) $this->success('OK', $row);
        }
        $this->error('非法操作');
    }

    /**
     * 积分明细
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认20条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1569510148","data":{"page":1,"total":7,"page_size":20,"total_page":1,"list":[{"title":"兑换 海天酱油 老抽王 ×2","score":-3600,"time":"2019-09-26 22:40"},{"title":"兑换 冰红茶 ×3","score":-20400,"time":"2019-09-26 22:39"},{"title":"兑换 天堂伞（丽华快餐纪念版） ×1","score":-5800,"time":"2019-09-26 22:14"},{"title":"兑换 金龙鱼 玉米油 ×1","score":-3600,"time":"2019-09-26 22:04"},{"title":"兑换 20元大红包 ×2","score":-2400,"time":"2019-09-25 23:55"},{"title":"兑换 冰红茶","score":-200,"time":"2019-09-18 16:25"},{"title":"订单完成 190925471838716","score":500,"time":"2019-09-18 10:31"}]}})
     */
    public function logs()
    {
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where['user_id'] = $this->auth->id;
        $total = ScoreLog::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $res = ScoreLog::where($where)->order('id', 'desc')->page($page, $page_size)->select();
            $list = [];
            foreach ($res as $k => $v) {
                $list[] = [
                    'title' => $v['memo'],
                    'score' => $v['score'],
                    'time'  => date('Y-m-d H:i', $v['createtime']),
                ];
            }
            $data['list'] = $list;
        }

        $this->success('OK', $data);
    }

}
